﻿using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;

public partial struct EventTriggerSystem : ISystem
{
    [BurstCompile]
    public void OnCreate(ref SystemState state)
    {
        state.RequireForUpdate<BattleSceneTag>();
    }

    public void OnUpdate(ref SystemState state)
    {
        var entity = SystemAPI.GetSingletonEntity<EventTriggerTag>();

        CurseKillUpdate(ref state, ref entity);
        EnemyDieUpdate(ref state);
    }

    private void CurseKillUpdate(ref SystemState state, ref Entity entity)
    {
        if (!SystemAPI.IsComponentEnabled<CurseKillAction>(entity))
            return;

        var enemyDieActionBuffer = SystemAPI.GetSingletonBuffer<EnemyDieAction>();
        
        foreach (var (enemyData, enemyEntity) in
                 SystemAPI.Query<RefRW<EnemyData>>().WithEntityAccess())
        {
            enemyDieActionBuffer.Add(new EnemyDieAction
            {
                EcsId = enemyData.ValueRO.EcsId,
                EnemyEntity = enemyEntity,
            });
        }

        // 触发后禁用
        SystemAPI.SetComponentEnabled<CurseKillAction>(entity, false);
    }

  

    //敌人死亡事件
    private void EnemyDieUpdate(ref SystemState state)
    {
        var enemyDieBuffer = SystemAPI.GetSingletonBuffer<EnemyDieAction>();
        if (enemyDieBuffer.IsEmpty)
            return;

        foreach (var enemyDieAction in enemyDieBuffer)
        {
            var enemyEntity = enemyDieAction.EnemyEntity;
            SystemAPI.SetComponentEnabled<PoolReceiveTag>(enemyEntity, true);

            //通知Mono对应的敌人脚本，可以处理死亡动画等
            // BattleState.Instance.EnemyGet(enemyDieAction.EcsId)?.TriggerDeath();
        }

        enemyDieBuffer.Clear();

    }


    
}